package com.zpf.dao.impl;

import com.zpf.dao.GoodsDao;
import com.zpf.pojo.Goods;
import com.zpf.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class GoodsDaoImpl implements GoodsDao {
    @Override
    public long findtotalCount(int typeId) {
        QueryRunner qf = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select count(0) from tb_goods where typeid = ? ";
        try {
            long count = (long) qf.query(sql,new ScalarHandler(),typeId);
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public List<Goods> findData(int typeId, int startIndex, int pageSize) {
        QueryRunner qf = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select id,name,pubdate, picture,price,star,intro,typeid from tb_goods where typeid = ? limit ?, ? ";
        try {
         List<Goods> goodsList =  qf.query(sql,new BeanListHandler<>(Goods.class),typeId,startIndex,pageSize);
            return goodsList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Goods findById(int id) {
        QueryRunner qf = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select id,name,pubdate, picture,price,star,intro,typeid from tb_goods where id=? ";
        try {
            Goods goods =  qf.query(sql,new BeanHandler<>(Goods.class),id);
            return goods;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
